import pymysql

class MySQLConnection:
    def __init__(self):
        """
        初始化数据库连接参数
        :param host: 数据库主机地址
        :param user: 数据库用户名
        :param password: 数据库密码
        :param db: 数据库名
        :param charset: 字符集
        """
        self.host = '192.168.162.5'
        self.user = 'skycloud'
        self.password = 'skycloud'
        self.db = 'hesm'
        self.charset = "utf8mb4"
        self.conn = None
        self.cursor = None

    def connect(self):
        """
        建立数据库连接
        """
        self.conn = pymysql.connect(
            host=self.host,
            user=self.user,
            password=self.password,
            db=self.db,
            charset=self.charset
        )
        self.cursor = self.conn.cursor()

    def execute_query(self, sql, params=None):
        """
        执行SQL查询
        :param sql: SQL语句
        :param params: 参数列表
        :return: 查询结果（列表中的元组）
        """
        self.cursor.execute(sql, params)
        return self.cursor.fetchall()
    
    

    def execute_command(self, sql, params=None):
        """
        执行SQL命令（非查询操作，如INSERT, UPDATE, DELETE）
        :param sql: SQL语句
        :param params: 参数列表
        :return: 影响的行数
        """
        self.cursor.execute(sql, params)
        return self.cursor.rowcount

    def commit(self):
        """Commit the current transaction."""
        if self.conn:
            self.conn.commit()

    def rollback(self):
        """Roll back the current transaction."""
        if self.conn:
            self.conn.rollback()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()

# 使用示例
#conn = MySQLConnection('localhost', 'your_username', 'your_password', 'your_database')
#conn.connect()
#result = conn.execute_query("SELECT * FROM your_table")
#for row in result:
#    print(row)
#conn.close()
